package main

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strings"
)

// getPwd 获取特定主机的密码
func getPwd(pwd_exe string, pwd_parm string) string {
	// option := "-u zonaxu 10.130.132.206"

	cmd := exec.Command("/bin/bash", "-c",
		fmt.Sprintf("%s %s", pwd_exe, pwd_parm)) // 执行脚本, 编译程序
	var out bytes.Buffer
	cmd.Stdout = &out // 将输出结果进行重定向
	err := cmd.Run()

	if err != nil {
		ErrHandler(err, Fault)
	}
	//fmt.Printf("The passwd is %s", out.String())
	return out.String()
}

func printServer(sc *IpConfType) {
	//	fmt.Printf("SHELL: ")
	PrintBeauty(fmt.Sprintf("ssh %s@%s\n%s", sc.User, sc.IP, sc.Pwd), 0)
}

func getServerStatement(conf *ServerConfType, patern string) {
	pat := []string{".*", patern, ".*"}
	var validIP = regexp.MustCompile(strings.Join(pat, ""))

	for _, sc := range conf.ServerConf {
		if validIP.MatchString(sc.IP) == false { // 未匹配到IP
			continue
		}
		if sc.Pwd == "" {
			sc.Pwd = getPwd(sc.PwdExe, sc.PwdParm)
		}
		printServer(&sc)
	}
}

func getDBStatement(conf *MySQLConfType, patern string) {
	pat := []string{".*", patern, ".*"}
	var validDB = regexp.MustCompile(strings.Join(pat, ""))

	for _, db := range conf.DB_ALL {
		if validDB.MatchString(db.DBName) == false {
			continue
		}
		fmt.Printf("mysql -h%s -P%s -u%s -p%s -D%s \n",
			db.Host, db.Port, db.User, db.Pwd, db.DBName)
	}
}

func myTest() {
	//fmt.Printf("\n%c[32m%s%c[0m\n\n", 0x1B, "testPrintColor", 0x1B)
}

func main() {
	ReadServerConf("./server.json")
	ReadMySQLConf("./mysql.yaml")
	argsWithProg := os.Args
	//argsWithoutProg := os.Args[1:]

	if len(argsWithProg) > 1 {
		fmt.Printf("Find pattern: [%s]\n", argsWithProg[1])
		getServerStatement(&serverConf, argsWithProg[1])
		getDBStatement(&dbConf, argsWithProg[1])
	}
}
